# -*- coding: utf-8 -
# Copyright 2008 by Benoît Chesneau <benoitc@e-engura.com>
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from couchdb_django.client import ResourceNotFound
from couchdb_django.middleware import local_
from couchdb_django.utils import datetime_tojson
from django.conf import settings
from django.contrib.sessions.backends.base import SessionBase
from django.core.exceptions import SuspiciousOperation


class SessionStore(SessionBase):
    def __init__(self, session_key=None):
        super(SessionStore, self).__init__(session_key)
    
    def load(self):
        s = None
        try:
            s = local_.db['session/%s' % self.session_key]
        except ResourceNotFound:
            pass

        if s is not None:
            try:
                return self.decode(s['session_data'])
            except SuspiciousOperation:
                pass
        self.session_key = self._get_new_session_key()
        self._session_cache = {}
        self.save()
        self.modified = True
        return {}
        
    def exists(self, session_key):
        s = None
        try:
            s = local_.db['session/%s' % session_key]
        except ResourceNotFound:
            pass
        if s is not None:
            return True
        return False
        
    def save(self):
        s = None
        try:
            s = local_.db['session/%s' % self.session_key]
        except ResourceNotFound:
            pass
            
        if s is not None:
            s['session_key'] = self.session_key
            s['session_data'] = self.encode(self._session)
            s['expire_date'] = datetime_tojson(self.get_expiry_date())
        else:
            s = {
                'session_key': self.session_key,
                'session_data': self.encode(self._session),
                'expire_date': datetime_tojson(self.get_expiry_date())
            }
        local_.db['session/%s' % self.session_key] = s
        
    def delete(self, session_key):
        try:
            del local_.db['session/%s' % session_key]
        except AttributeError:
            pass
            
